use log::info;
use serde::Deserialize;
use serde_json::json;
use crate::features::{docker::{execute::{create_execute, run_command, start_execute}, model::Container}, rabbitmq::{model::{HandleStatus}, producer::instance::send}};
use crate::features::docker::execute::remove_execute;

#[derive(Deserialize)]
struct Execute {
    id: String,
    command: Option<String>
}

pub async fn display_create_execute(handle_status: HandleStatus) {
    if let Some(ref data) = handle_status.data {
        if let Ok(container)= serde_json::from_str::<Container>(data.as_str()) {
            match create_execute(container.id.unwrap()).await {
                Ok(res) => {
                    let handle_status= HandleStatus::from(handle_status)
                        .set_data(json!({
                            "executeId": res.id
                        }));
                    send(handle_status.recv.clone().as_str(), handle_status).await;
                }
                Err(_) => {}
            };
        }
    }
}

pub async fn display_start_execute(handle_status: HandleStatus) {
    if let Some(ref data) = handle_status.data {
        info!("data => {}", data);
        if let Ok(execute)= serde_json::from_str::<Execute>(data.as_str()) {
            match start_execute(execute.id, handle_status.clone()).await {
                Ok(_) => {
                    let handle_status= HandleStatus::from(handle_status);
                    send(handle_status.recv.clone().as_str(), handle_status).await;
                },
                Err(_) => {

                },
            }
        }
    }
}

pub async fn display_run_execute(handle_status: HandleStatus) {
    if let Some(data) = handle_status.data {
        info!("data => {}", data);
        if let Ok(execute)= serde_json::from_str::<Execute>(data.as_str()) {
            run_command(execute.id, execute.command.unwrap()).await;
        }
    }
}

pub async fn display_remove_execute(handle_status: HandleStatus) {
    if let Some(ref data) = handle_status.data {
        info!("data => {}", data);
        if let Ok(execute)= serde_json::from_str::<Execute>(data.as_str()) {
            match remove_execute(execute.id).await {
                Ok(_) => {
                    let handle_status= HandleStatus::from(handle_status);
                    send(handle_status.recv.clone().as_str(), handle_status).await;
                }
                Err(_) => {}
            }
        }
    }
}